<?php
/**
 * Created by PhpStorm.
 * User: moonlight
 * Date: 2015/6/2
 * Time: 23:13
 */

namespace Home\Controller;


use Think\Controller;

/**
 * Class BlogController
 * @package Home\Controller
 * @function index(),publish(),
 *
 */

class BlogController extends Controller{
    /**
     * 论坛主页..注意论坛首页展示的是“寻找” area_id = 2
     */
    public function index(){
        R('Index/isSession');
        $area_id = 2;
        $blog_list  =   $this->blogLists($area_id);//获取论坛信息
        //dump($blog_list);
        $this->assign('blog_list',$blog_list);
        $this->display();
    }

    /**
     * 进入招领界面
     */
    public function foundIndex(){
        R('Index/isSession');
        $area_id = 1;
        $blog_list  =   $this->blogLists($area_id);//获取论坛信息
        //dump($blog_list);
        $this->assign('blog_list',$blog_list);
        $this->display();
    }
    public function energyIndex(){
        R('Index/isSession');
        $area_id = 3;
        $blog_list  =   $this->blogLists($area_id);//获取论坛信息
        //dump($blog_list);
        $this->assign('blog_list',$blog_list);
        $this->display('energyIndex');
    }
    public function negativeEnergyIndex(){
        R('Index/isSession');
        $area_id = 4;
        $blog_list  =   $this->blogLists($area_id);//获取论坛信息
        //dump($blog_list);
        $this->assign('blog_list',$blog_list);
        $this->display('negativeEnergyIndex');
    }
    /**
     * 获得单贴数据并进行相关处理
     * @prama $blog_id
     * @return array
     */
    public function getPosts($blog_id){
        $Blog = D('Blog');//实例化blog
        $blogData = $Blog->getBlogData($blog_id);//获取blog信息，注意，以后像这样情况如果不使用关联模型进行多表查询的话，还是逐个获取信息比较好，这样便于查错，流程清晰
        //获取用户信息
        $User = D('User');//实例化user

        $userData   =   $User->getUserData($blogData['user_id']);//获取用户信息
        //dump($userData);

        $Goods  =   D('Goods');
        $goodsData  =   $Goods->getGoodsData($blogData['blog_id']);//获取good信息,主要good表以blog_id做主键
        //获得回复信息
        $replyData  =   D('Blog')->getReplies($blogData['blog_id']);
        $replyData['reply_list'] = R('User/idToName',array($replyData['reply_list']));

        //将信息放入$posts数组
        $posts  =   array(
            'user'  =>  $userData,
            'blog'  =>  $blogData,
            'goods' =>  $goodsData,
            'replies'   =>  $replyData['reply_list'],
            'page'  =>  $replyData['page'],
        );
        //dump($posts['replies']);
        if($posts){
            return  $posts;
        }
        return false;
    }

    /**
     * find 主题帖入口
     */
    public function findPosts($blog_id){
        R('Index/isSession');//session会话管理
        //dump('11111');
        $posts  =   $this->getPosts($blog_id);//调用posts方法进行数据处理
        if($posts){
            $this->assign('posts',$posts);
            $floor_count    =   1;
            $this->assign('floor_count',$floor_count);
            //dump($posts);die;
            $this->display('findPosts');
        }else{
            $this->error('内容获取失败');
        }
    }
    /**
     * found主题posts入口
     */
    public function foundPosts($blog_id){
        R('Index/isSession');//session会话管理
        $posts  =   $this->getPosts($blog_id);//调用posts方法进行数据处理
        if($posts){
            $this->assign('posts',$posts);
            $floor_count    =   1;
            $this->assign('floor_count',$floor_count);
            $this->display('foundPosts');
        }else{
            $this->error('内容获取失败');
        }
    }
    public function energyPosts($blog_id){
        R('Index/isSession');//session会话管理
        $posts  =   $this->getPosts($blog_id);//调用posts方法进行数据处理
        if($posts){
            $this->assign('posts',$posts);
            $floor_count    =   1;
            $this->assign('floor_count',$floor_count);
            $this->display('energyPosts');
        }else{
            $this->error('内容获取失败');
        }
    }
    public function negativeEnergyPosts($blog_id){
        R('Index/isSession');//session会话管理
        $posts  =   $this->getPosts($blog_id);//调用posts方法进行数据处理
        if($posts){
            $this->assign('posts',$posts);
            $floor_count    =   1;
            $this->assign('floor_count',$floor_count);
            $this->display('negativeEnergyPosts');
        }else{
            $this->error('内容获取失败');
        }
    }
    /**
     * 获取论坛列表
     * @author moonlight
     * @param $area_id 区域id
     */
    public function blogLists($area_id){
        $blog_list = D('Blog')->getBlogList($area_id);

        $blog_list['lists'] = R('User/idToName',array($blog_list['lists']));//获取用户名!!!为什么用R方法传过去的二维数组就变成一维了？？？？？？原来要加array()
        return $blog_list;
    }
    //ajax获取入口
//    public function getBlogLists($area_id){
//        $blog_list = D('Blog')->getBlogList($area_id,0);
//        $blog_list = R('User/idToName',array($blog_list));
//        foreach($blog_list as & $value){
//            $value['blog_date']    =   date('Y-m-d H:i:s',$value['blog_date']);
//        }
//        $this->ajaxReturn($blog_list);
//    }
    /**
     * 发布信息选择页面
     */
    public function publish()
    {
        R('Index/isSession');
        //$this->display();die;
        if (session('?username')) {
            //判断用户信息是否完善
            $result = D("User")->isComplete();
            //dump($result);die;
            if($result){
                $this->display();
            }
            $this->error('抱歉，请您先完善您的用户信息（学号，联系方式！）',U('User/userManage'),5);
        } else {              //未登录状态不能发布消息
            $this->error('抱歉！您还未登录', U('User/login'), 3);
        }

    }
    public function pubLostInfo(){
        R('Index/isSession');
        $this->display();
    }
    public function pubFoundInfo(){
        R('Index/isSession');
        $this->display();
    }
    public function pubEnergyInfo(){
        R('Index/isSession');
        $this->display();
    }
    public function pubNegativeEnergyInfo(){
        R('Index/isSession');
        $this->display();
    }
    /**
     * 发布寻物信息
     * @param $area_id=1 招领 =2失物 3正能量 4负能量
     */
    public function pubInfo($area_id)
    {
        R('Index/isSession');
        if (!IS_POST) {
            if($area_id==2){
                $this->redirect('Blog/pubLostInfo',0);
            }
            if($area_id==1){
                $this->redirect('Blog/pubFoundInfo',0);
            }
            if($area_id==3){
                $this->redirect('Blog/pubEnergyInfo',0);
            }
            if($area_id==4){
                $this->redirect('Blog/pubNegativeEnergyInfo',0);
            }
        } else {
            $data = I('post.');
            $data['area_id'] = $area_id;
            //写入blog
            $Blog = D('Blog'); //实例化blog模型
            $msg = $Blog->publishBlog($data);
            if ($msg['status'] == 0) {
                $this->error($msg . info);
            } else { //博客写入成功
                $files  =   $_FILES;
                if('' == $files['energy_blog_picture']['name'] && ($area_id==3||$area_id==4)){
                    //dump('1');die;
                    $this->success('发布成功!',U('Home/Blog/energyIndex'),3);
                }
                //图片上传
                $config = array(
                    'maxSize' => 3145728,//<3M
                    'savePath' => '/Public/Uploads/Photos',//绝对路径。finder/Upload/Public/Uploads/..
                    'saveName' => array('uniqid', ''),
                    'exts' => array('jpg', 'gif', 'png', 'jpeg'),
                    'autoSub' => true,
                    'subName' => array('date', 'Ymd'),
                );
                $upload = new \Think\Upload($config);// 实例化上传类

                $info = $upload->upload();
                if (!$info) {// 上传错误提示错误信息
                    $this->error($upload->getError());
                } else {// 上传成功  写入goods表
                    if($area_id==3 ||$area_id==4){
                        $imgName = $info['energy_blog_picture']['savename'];
                        $imgPath = $info['energy_blog_picture']['savepath'];
                        $blogData['energy_blog_picture'] = $imgPath . $imgName;
                        $blogData['blog_id'] = $msg['blog_id'];
                        //dump($this);die;
                        $Blog = D('Blog');
                        $Blog->addBlogInfo($blogData);
                        //$Blog = new BlogController();

                    }else{
                        $imgName = $info['goods_picture']['savename'];
                        $imgPath = $info['goods_picture']['savepath'];
                        $goodsData = $data;                              //将表单信息赋给$goodsData
                        $goodsData['goods_picture'] =  $imgPath . $imgName;//图片存储内容为 路径+图片名
                        $goodsData['blog_id'] = $msg['blog_id'];

                        $Goods = D('Goods');     //实例化goods
                        if(!($Goods->addGoods($goodsData))){    //发布失败
                            $this->error('发布失败!');
                        }
                    }
                        if($area_id==2){
                            $this->redirect('Blog/index',0);
                            //$this->success('发布成功!','Home/Blog/index',3);
                        }
                        if($area_id==1){
                            $this->redirect('Blog/foundIndex',0);
                           // $this->success('发布成功!','Home/Blog/foundIndex',3);
                        }
                        if($area_id==3){
                            $this->redirect('Blog/energyIndex',0);
                            //dump($this);die;
                            //$this->success('发布成功!','Home/Blog/energyIndex',3);die;
                        }
                        if($area_id==4){
                            $this->redirect('Blog/negativeEnergyIndex',0);
                           // $this->success('发布成功!','Home/Blog/negativeEnergyIndex',3);die;
                        }

                    exit;
                }

            }


        }

    }

    /**
     * 发布回复
     */
    public function reply($area_id){
        $replyData  =   I('post.');
        R('Index/isSession');
        if (session('?username')) {
            //判断用户信息是否完善
            $result = D("User")->isComplete();
            if($result){
                $replyReturn    =   D('Blog')->addReply($replyData);
                if($replyReturn['msg']['status'] == 0){
                    return $replyReturn['msg'];
                }else{
                    if($replyData['reply_type'] == 1){//回复的回复

                    }else{
                        D('Blog')->addReplyInfo($replyData);//添加回复数，最近回复
                        $Blog = new BlogController();
                        if($area_id == 1) $Blog->foundPosts($replyData['blog_id']);
                        if($area_id == 2) $Blog->findPosts($replyData['blog_id']);
                        if($area_id == 3) $Blog->energyPosts($replyData['blog_id']);
                        if($area_id == 4) $Blog->negativeEnergyPosts($replyData['blog_id']);
                    }
                }
            }else{
                $this->error('抱歉，请您先完善您的用户信息（学号，联系方式！）',U('User/userManage'),5);
            }
        } else {              //未登录状态不能发布消息

            $this->error('抱歉！您还未登录', U('User/login'), 3);
        }

    }

    public function blogSearch(){
        $searchData =   I('post.');
        if(empty($searchData['search_content'])){
            $this->error('搜索内容不能为空',U('Home/Blog/index'),5);
        }else{
            $result = D('Blog')->blogSearch($searchData);
            $this->assign('result',$result);
            $this->display();
        }
    }
}